﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Concurrency;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MusicStore.Messages;
using MusicStore.Models;
using ReactiveUI;

namespace MusicStore.ViewModels
{
    public partial class MainWindowViewModel : ViewModelBase
    {
        public ObservableCollection<AlbumViewModel> Albums { get; } = new();


        public ICommand BuyMusicCommand { get; }

        public MainWindowViewModel()
        {
            BuyMusicCommand = ReactiveCommand.Create(async () =>
            {
                // 当按钮被点击时，这里的代码将被执行。
                //await AddAlbumAsync();
                await BuyMusicAsync();
            });
            RxApp.MainThreadScheduler.Schedule(LoadAlbums);
        }

        private async Task BuyMusicAsync()
        {
            try
            {
                // 发送消息来打开音乐商店对话框
                var album = await WeakReferenceMessenger.Default.Send(new PurchaseAlbumMessage());

                if (album != null)
                {
                    // 将返回的专辑添加到集合中
                    Albums.Add(album);

                    await album.SaveToDiskAsync();

                    // 可选：加载专辑封面
                    await album.LoadCoverAsync();
                }
            }
            catch (Exception ex)
            {
                // 处理异常（例如用户取消对话框）
                System.Diagnostics.Debug.WriteLine($"购买音乐时出错: {ex.Message}");
            }
        }



        [RelayCommand]
        private async Task AddAlbumAsync()
        {
            // Send the message to the previously registered handler and await the selected album
            var album = await WeakReferenceMessenger.Default.Send(new PurchaseAlbumMessage());
        }

        private async void LoadAlbums()
        {
            var albums = (await Album.LoadCachedAsync()).Select(x => new AlbumViewModel(x));

            foreach (var album in albums)
            {
                Albums.Add(album);
            }

            foreach (var album in Albums.ToList())
            {
                await album.LoadCoverAsync();
            }
        }
    }
}
